package com.alvis.media.controller.admin;

import com.alvis.media.base.BaseApiController;
import com.alvis.media.base.RestResponse;
import com.alvis.media.domain.FileInfo;
import com.alvis.media.domain.User;
import com.alvis.media.service.FileInfoService;
import com.alvis.media.utility.DateTimeUtil;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.UUID;
//文件管理（增删改查）
@RestController
@RequestMapping("/api/admin/file")
@AllArgsConstructor
public class FileManagementController extends BaseApiController {

    private final FileInfoService fileInfoService;

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public RestResponse<FileInfo> uploadFile(@RequestParam("file") MultipartFile file,
                                             @RequestParam(value = "description", required = false) String description) {
        try {
            if (file.isEmpty()) {
                return RestResponse.fail(400, "文件不能为空");
            }

            // 获取当前登录用户
            User currentUser = getCurrentUser();

            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                return RestResponse.fail(400, "文件名不能为空");
            }

            // 处理文件名，避免重名：在文件名前加时间戳
            String timestamp = String.valueOf(System.currentTimeMillis());
            String fileExtension = "";
            String baseFileName = originalFilename;
            
            if (originalFilename.contains(".")) {
                int lastDotIndex = originalFilename.lastIndexOf(".");
                baseFileName = originalFilename.substring(0, lastDotIndex);
                fileExtension = originalFilename.substring(lastDotIndex);
            }
            
            // 最终文件名：时间戳_原始文件名
            String fileName = timestamp + "_" + baseFileName + fileExtension;

            // 获取项目根目录的绝对路径
            String projectPath = System.getProperty("user.dir");
            String uploadDir = projectPath + File.separator + "uploads";
            
            // 创建uploads目录
            File uploadDirFile = new File(uploadDir);
            if (!uploadDirFile.exists()) {
                boolean created = uploadDirFile.mkdirs();
                if (!created) {
                    return RestResponse.fail(500, "创建文件目录失败");
                }
            }

            // 保存文件（使用绝对路径）
            File targetFile = new File(uploadDirFile, fileName);
            file.transferTo(targetFile);

            // 构建文件URL（直接使用文件名）
            String fileUrl = fileName;

            // 保存文件信息到数据库
            FileInfo fileInfo = new FileInfo();
            fileInfo.setFileName(originalFilename);
            fileInfo.setFileUrl(fileUrl);
            fileInfo.setCreateId(currentUser.getId());
            fileInfo.setCreateTime(new Date());
            fileInfo.setLastModifyTime(new Date());

            fileInfoService.saveFileInfo(fileInfo);

            return RestResponse.ok(fileInfo);

        } catch (IOException e) {
            e.printStackTrace();
            return RestResponse.fail(500, "文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 文件下载
     */
    @GetMapping("/download/{fileId}")
    public void downloadFile(@PathVariable Integer fileId, HttpServletResponse response) {
        try {
            // 查询文件信息
            FileInfo fileInfo = fileInfoService.getFileById(fileId);
            if (fileInfo == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("文件不存在");
                return;
            }

            // 构建完整文件路径（使用绝对路径）
            String projectPath = System.getProperty("user.dir");
            String filePath = projectPath + File.separator + "uploads" + File.separator + fileInfo.getFileUrl();
            File file = new File(filePath);

            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("文件不存在");
                return;
            }

            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            String encodedFileName = URLEncoder.encode(fileInfo.getFileName(), "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
            response.setContentLengthLong(file.length());

            // 读取文件并写入响应流
            try (FileInputStream fis = new FileInputStream(file);
                 OutputStream os = response.getOutputStream()) {
                
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.flush();
            }

        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("文件下载失败：" + e.getMessage());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 获取文件列表（分页）
     */
    @PostMapping("/list")
    public RestResponse<PageInfo<FileInfo>> getFileList(
            @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "fileName", required = false) String fileName,
            @RequestParam(value = "createId", required = false) Integer createId) {
        
        PageInfo<FileInfo> pageInfo = fileInfoService.getFileListPage(pageIndex, pageSize, fileName, createId);
        return RestResponse.ok(pageInfo);
    }

    /**
     * 获取当前用户的文件列表
     */
    @GetMapping("/myFiles")
    public RestResponse<PageInfo<FileInfo>> getMyFiles(
            @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        
        User currentUser = getCurrentUser();
        PageInfo<FileInfo> pageInfo = fileInfoService.getFileListPage(pageIndex, pageSize, null, currentUser.getId());
        return RestResponse.ok(pageInfo);
    }

    /**
     * 根据ID获取文件信息
     */
    @GetMapping("/info/{fileId}")
    public RestResponse<FileInfo> getFileInfo(@PathVariable Integer fileId) {
        FileInfo fileInfo = fileInfoService.getFileById(fileId);
        if (fileInfo == null) {
            return RestResponse.fail(404, "文件不存在");
        }
        return RestResponse.ok(fileInfo);
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/delete/{fileId}")
    public RestResponse<String> deleteFile(@PathVariable Integer fileId) {
        try {
            // 查询文件信息
            FileInfo fileInfo = fileInfoService.getFileById(fileId);
            if (fileInfo == null) {
                return RestResponse.fail(404, "文件不存在");
            }

            // 删除物理文件（使用绝对路径）
            String projectPath = System.getProperty("user.dir");
            String filePath = projectPath + File.separator + "uploads" + File.separator + fileInfo.getFileUrl();
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }

            // 删除数据库记录
            fileInfoService.deleteFile(fileId);

            return RestResponse.ok("文件删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(500, "文件删除失败：" + e.getMessage());
        }
    }
}
